<?php
ini_set('memory_limit', '500M'); //协程会耗费较多的内存

define('MAX_MYSQLPOOL_NUM', 50); //mysql最大连接数，即并发数
define('TESTCOUNT', 1000);  //一共的测试次数

$mysqlconf = [
    'host' => '120.31.136.107',
    'port' => 3306,
    'user' => 'root',
    'password' => 'd23a048282d9f0e3',
    'database' => 'system_pay',
    'timeout' => 10
];
//
Swoole\Coroutine::create(function () use ($mysqlconf) {
    $stime = microtime(true); //程序开始时间

    $pool = new MysqlPool($mysqlconf);
    $chan = new chan(MAX_MYSQLPOOL_NUM); //并发数，协程间使用channel通信

    for ($i = 1; $i < TESTCOUNT + MAX_MYSQLPOOL_NUM; $i++) {
        $chan->push('x');
        Swoole\Coroutine::create(function () use ($pool, $chan, $i) {
            //测试的业务逻辑开始
            $conn = $pool->get();
            if ($conn) {
                $sql = "select * from pay_order where id in (" . implode(',', getRandpid()) . ')';
                $time1 = microtime(true);
                $conn->query($sql);
                $time2 = microtime(true);

                if ($i % intval(TESTCOUNT / 10) == 0) { //输出执行的进度
                    echo "\n finish $i / " . TESTCOUNT;
                }
                $pool->put($conn, (($time2 - $time1) * 1000)); //每次查询耗时就不单独做实例，直接修改连接池类做简单统计
            } else {
                echo "\n connect mysql fail，跳过SQL";
            }
            //业务逻辑结束
            $chan->pop();
        });
    }
    $etime = microtime(true);
    echo "\n ============执行结果=============";
    echo "\n 并发数量： " . MAX_MYSQLPOOL_NUM;
    echo "\n 查询次数： " . TESTCOUNT;
    echo "\n 执行总耗时： " . intval($etime - $stime) . "秒\n";

    echo "\n QPS (查询次数/总耗时) :" . intval((TESTCOUNT / ($etime - $stime)));
    echo "\n 每次查询耗时平均值：" . intval($pool->alltime / TESTCOUNT) . "ms";
    echo "\n ============end=============\n";
    die;
});


//数据库连接池，https://wiki.swoole.com/wiki/page/852.html
class MysqlPool
{
    protected $pool;
    private $mysqlconf;
    public $alltime;

    public function __construct($mysqlconf)
    {
        $this->pool = new SplQueue();
        $this->mysqlconf = $mysqlconf;
        $this->alltime = 0;
    }

    public function put($mysql, $time = 0)
    {
        $this->pool->push($mysql);
        $this->alltime += $time;
    }

    public function get()
    {
        //有空闲连接
        if (count($this->pool) > 0) {
            return $this->pool->pop();
        }

        $mysqlconf = $this->mysqlconf;
        $mysql = mysqli_connect($mysqlconf['host'], $mysqlconf['user'], $mysqlconf['password'], $mysqlconf['database']);
        if (!$mysql) {
            echo "\n connect error info: " . mysqli_error($mysql). "\n";
            return false;
        } else {
            return $mysql;
        }
    }
}

//随机生成的数字
function getRandpid()
{
    for ($i = 0; $i < 40; ++$i) {
        $ret[] = rand(1, 18572);
    }
    return $ret;
}
